<?php

namespace app\home\controller;

use app\common\model\Article as ArticleModel;
use app\common\model\Cate as CateModel;

class Index extends HomeCommon
{
    public function index()
    {
        $cateModel = new CateModel();
        $parentsList = $cateModel->where(['pid' => 0,'id'=>['<>',1]])->order(['cate_sort' => 'desc'])->select();
        $floors = [];
        $floor_names = [];
        if ($parentsList) {
            foreach ($parentsList as $k => $v) {

                $res = $this->getFloor($v['id']);
                if ($res) {
                    $floors[] = $res;
                    $floor_names[] = $v['cate_name'];
                }
            }
        }
        $this->assign('floor_names',$floor_names);
        $this->assign('floor_count',count($floors));
        $this->assign('floors', $floors);
        return $this->fetch();
    }

    public function aboutus()
    {
        $this->assign('article', ArticleModel::get(['cate_id' => 1]));
        return $this->fetch();
    }

    private function getFloor($id)
    {
        $cateModel = new CateModel();
        $articleModel = new ArticleModel();
        $children = $cateModel->query(sprintf('select group_concat(id) as str from %s where pid=%d', $cateModel->getTable(), $id));
        if ($children && $children[0]['str']) {
            $str = $children[0]['str'] . ',' . $id;
            $where['cate_id'] = ['in', [$str]];
        } else {
            $where['cate_id'] = $id;
        }

        $result = $articleModel->where($where)->order(['article_sort' => 'desc'])->limit(0,12)->select();

        if ($result) {
            return $result->toArray();
        }
        return [];
    }
}
